Skip to main content
查利博客

142. Linked List Cycle II

Question Link: https://leetcode.com/problems/linked-list-cycle-ii/description/

Thinking:

Denote

AB: Distance from head to the starting node of the cycle
BC: Distance from the starting node of the cycle to the collision in cycle
P: Perimiter of the cycle
n: Number of cycles fast pointer travel before collide with slow pointer

As 2 * no. of steps slow pointer take = no. of steps faster pointer take
Then 2 * (AB + BC) = AB + BC + nP
So AB = nP - BC

Hence we observer that when the fast pointer and slow pointer meet, a new pointer travel from head to the starting node of the cycle (AB) will meet the slow pointer.

Java Code #

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast, slow;
        fast = slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                while (head != slow) {
                    head = head.next;
                    slow = slow.next;
                }
                return head;
            }
        }
        return null;
    }
}

C Code #

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *detectCycle(struct ListNode *head) {
    if (head == NULL || head->next == NULL)
        return NULL;

    struct ListNode* walker1 = head;
    struct ListNode* runner = head;

    while (runner != NULL && runner->next != NULL) {
        walker1 = walker1->next;
        runner = runner->next->next;
        if (walker1 == runner) {
            struct ListNode* walker2 = head;
            while (walker1 != walker2) {
                walker1 = walker1->next;
                walker2 = walker2->next;
            }
            return walker1;
        }
    }

    return NULL;
}